<template>
  <div class="scene-edifice-box">
    <el-form ref="form" :model="formData" :disabled="popConfig.disabled" :rules="rules" label-width="110px">
      <template v-for="(item, index) in formList">
        <el-form-item
          :key="`${item.prop}${index}`"
          :style="item.itemStyle || {}"
          :label="item.name"
          :prop="item.prop"
          :class="item.itemClass"
        >
          <component
            :is="item.componentType || 'el-input'"
            v-if="item.prop"
            v-model="formData[item.prop]"
            :clearable="true"
            :class="item.class"
            v-bind="item.attrConfig || {}"
            @change="handlerSelectData(item)"
            @changeImg="changeImg"
          >
            <template v-for="option in item.optionList">
              <el-option
                :key="option.code"
                :label="option.name"
                :value="option.code"
              />
            </template>
          </component>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import api from '@/api/apis/sceneFloor'
import AddImg from '@/components/PopItems/add-img.vue'

export default {
  name: 'AddSceneEdifice',
  mixins: [dictMixin],
  components: { AddImg },
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isAdd: true,
      formData: {},
      formList: [
        {
          name: '楼层Id',
          prop: 'id',
          componentType: 'el-input',
          attrConfig: {
            disabled: true,
          },
        },
        {
          name: '楼层名称',
          prop: 'floorName',
          attrConfig: { placeholder: '请输入楼层名称' }
        },
        {
          name: '建筑面积(m²)',
          prop: 'floorArea',
          attrConfig: { placeholder: '请输入建筑面积' }
        },
        {
          name: '背景图',
          prop: 'backgroundImg',
          componentType: 'AddImg',
          attrConfig: { tip: '请上传jpg/png文件，且不超过5MB,建议尺寸1800px * 900px' }
        }
      ]
    }
  },
  computed: {
    rules() {
      const validateNumber = (rule, value, callback) => {
        const numberReg = /^-?[0-9]\d*$/
        let msg = ''
        if (value !== '') {
          if (!numberReg.test(value)) {
            msg = '请输入整数'
          } else if (value === '0') {
            msg = '建筑面积不能是0'
          }
        } else {
          msg = '请输入建筑面积'
        }
        msg ? callback(new Error(msg)) : callback()
      }
      return {
        floorName: [{ required: true, message: '请输入楼层名称', trigger: 'blur' }],
        floorArea: [{ required: true, trigger: 'blur', validator: validateNumber }]
      }
    }
  },
  watch: {
    popData: {
      handler(data) {
        this.isAdd = !data.id
        this.formList.forEach((e) => {
          this.$set(this.formData, e.prop, data[e.prop])
        })
        this.$set(this.formData, 'id', data.id)
        if (data.backgroundImg != null) {
          this.formList[3].attrConfig.defaultFileList = [data.backgroundImg]
        }
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      this.submit(params)
    }
  },
  methods: {
    changeImg(key, value) {
      this.$set(this.formData, 'backgroundImgFile', value)
    },
    /**
     * change事件
     */
    handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }
    },
    /**
     * 提交
     */
    submit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.formData.backgroundImgFile) {
            const formData = new FormData()
            formData.append('file', this.formData.backgroundImgFile.raw)
            const urlRes = await this.$api.fileManage.baseUploadData(
              '/energy-carbon/grass-file/file/upload',
              formData
            )
            if (Number(urlRes.code) === 1000) {
              params.backgroundImg = urlRes.data
            }
          }
          const res = await this.$api.sceneFloor[ this.isAdd ? 'add' : 'update' ](params)
          if (Number(res.code) === 1000) {
            this.$message.success(`${this.isAdd ? '新增' : '编辑' }成功！`)
            this.$emit('onFinish', 'scene-floor-add')
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
//.scene-edifice-box {
//  color: #333;
//  padding: 0 20px;
//
//  ::v-deep .el-form {
//    display: flex;
//    flex-wrap: wrap;
//    justify-content: space-between;
//
//    .lable-head {
//      .el-form-item__label {
//        border-left-style: solid;
//        border-left-width: 5px;
//        border-left-color: var(--button-default-color);
//        text-align: left;
//        padding-left: 10px;
//      }
//    }
//
//    .floor-input {
//      color: #666;
//      font-weight: bold;
//      font-size: 14px;
//      //margin-bottom: 30px;
//
//      .input {
//        line-height: 30px;
//      }
//    }
//
//    .floor-div {
//      max-height: 300px;
//      overflow: auto;
//    }
//
//    .el-form-item {
//      width: calc(50% - 10px);
//
//      &.width100p {
//        width: 100%;
//      }
//
//      .el-form-item__label {
//        color: #666;
//        font-size: 14px;
//      }
//
//      &.form-sub-title {
//        width: 100%;
//
//        .el-form-item__label {
//          display: flex;
//          align-items: center;
//          justify-content: flex-start;
//          font-weight: bold;
//          color: #333;
//          font-size: 16px;
//          line-height: 1;
//
//          &::before {
//            content: '';
//            display: inline-block;
//            width: 4px;
//            height: 15px;
//            background-color: #00858d;
//            margin-right: 5px;
//          }
//        }
//      }
//    }
//
//    .el-select,
//    .el-cascader {
//      width: 100%;
//    }
//  }
//}
</style>
